<?php
  namespace UserForm\Controller;
  use Zend\Mvc\Controller\AbstractActionController;
  use Zend\View\Model\ViewModel;
  use UserForm\Form\RegisterForm;
  use UserForm\Form\RegisterFilter;
  use UserForm\Model\User;
  use UserForm\Model\UserTable;

  class RegisterController extends AbstractActionController
  {
     public function indexAction()
     {
       $form=new RegisterForm();
       $viewModel=new ViewModel(array('form' => $form));
       return $viewModel;
     }

     public function confirmAction()
     {
        // $viewModel=new ViewModel();
         $form=new RegisterForm();
         $viewModel=new ViewModel(array('form' => $form));
         return $viewModel;
     }
     public function processAction()
     {
         if (!$this->request->isPost()) {
             return $this->redirect()->toRoute(NULL, array('controller' => 'register', 'action' => 'index'));
         }
         $post = $this->request->getPost();
         $form = new RegisterForm();
         $inputFilter = new RegisterFilter();
         $form->setInputFilter($inputFilter);
         $form->setData($post);
         if (!$form->isValid()) {
             $model = new ViewModel(array('error' => true, 'form' => $form,));
             $model->setTemplate('userform/register/index');
             return $model;  // 轮个 return 语㮥繮䬮㮽䮰䮧蟮
         }
         // 以䶮代瞮㮨表㬮騮譮笮轮䮶䮧蟮
        $this->createUser($form->getData());  
        return $this->redirect()->toRoute(NULL, array('controller' => 'register', 'action' => 'confirm'));
     }
     public function testAction()
     {
         $viewModel=new ViewModel();
         return $viewModel;
     }
     protected function createUser(array $data)
    {
      $sm = $this->getServiceLocator();
      $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
      $resultSetPrototype = new \Zend\Db\ResultSet\ResultSet();
      $tableGateway = new \Zend\Db\TableGateway\TableGateway('userform', $dbAdapter, null, $resultSetPrototype);
      $user = new User();
      $user->exchangeArray($data);
      $userTable = new UserTable($tableGateway);
      $userTable->saveUser($user);
      return true;
   }

    }

